<template>
    <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>
            <a href="/">基础数据</a>
        </el-breadcrumb-item>
        <el-breadcrumb-item>网格人员</el-breadcrumb-item>
    </el-breadcrumb>
{{ selections }}
    <div style="border: 1px solid #ccc; padding: 8px; margin-top: 12px;">
        <!-- {{ formInline }} ---
        {{ tableData }} -->
        <el-form :inline="true" :model="formInline" class="demo-form-inline">
            <el-form-item label="真实姓名">
                <el-input v-model="formInline.RealName" placeholder="请输入真实姓名" clearable />
            </el-form-item>


            <el-form-item label="选择部门">


                <el-cascader v-model="formInline.DepartmentId" :options="options" :props="props" />
            </el-form-item>

            <el-form-item>
                <el-button type="primary" @click="search">查询</el-button>
                <el-button type="danger" @click="reset">重置</el-button>

            </el-form-item>
        </el-form>
    </div>
    <div style="border: 1px solid #ccc; padding: 8px; margin-top: 12px;">
        <el-button type="success" size="small" @click="addDialog = true">添加</el-button>
 
        <el-table   @selection-change="handleSelectionChange" :data="tableData" style="width: 100%">
                <!-- 复选框列 -->
             <el-table-column type="selection" width="55" />
            <el-table-column type="index" label="序号" width="90" />
            <el-table-column prop="accountName" label="账号" width="120" />
            <el-table-column prop="realName" label="姓名" width="100" />
            <el-table-column prop="phoneNo" label="联系方式" width="120" />
            <el-table-column prop="cardId" label="身份证号" width="190" />
            <el-table-column prop="roleName" label="角色" width="90" />
            <el-table-column prop="departmentName" label="所属部门" width="150" />

            <el-table-column fixed="right" label="操作" min-width="140">
                <template #default="scope">
                    <el-button type="primary" size="small" @click="toEdit(scope.row)">
                        编辑
                    </el-button>
                    <el-button type="danger" size="small" @click="del(scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination v-model:current-page="page.PageIndex" v-model:page-size="page.PageSize"
            :page-sizes="[3, 4, 5, 6, 7, 8]" layout="total, sizes, prev, pager, next, jumper" :total="page.totalCount"
            prev-text='上一页' next-text="下一页" />

    </div>

    <!-- 添加弹窗区域 -->
    <el-dialog v-model="addDialog" title="添加网格人员" width="500">
        <!-- {{ ruleForm }} -->
        <el-form ref="ruleFormRef" style="max-width: 600px" :model="ruleForm" :rules="rules" label-width="auto">
            <el-form-item label="部门名称" style="width: 460px;" prop="departmentId">

                <el-cascader style="width: 460px;" v-model="ruleForm.departmentId" :options="options1"
                    :props="props1" />
            </el-form-item>
            <el-form-item label="姓名" prop="realName">
                <el-input v-model="ruleForm.realName" />
            </el-form-item>
            <el-form-item label="身份证号" prop="cardId">
                <el-input v-model="ruleForm.cardId" />
            </el-form-item>
            <el-form-item label="联系方式" prop="phoneNo">
                <el-input v-model="ruleForm.phoneNo" @blur="setAccount()" />
            </el-form-item>

            <el-form-item label="账号" prop="accountName">
                <el-input v-model="ruleForm.accountName" />
            </el-form-item>

            <el-form-item label="角色" prop="roleId">
                <el-radio-group v-model="ruleForm.roleId">
                    <el-radio :value="3">网格长</el-radio>
                    <el-radio :value="4">网格员</el-radio>
                </el-radio-group>
            </el-form-item>

            <el-form-item>
                <el-button type="primary" @click="submitForm(ruleFormRef)">
                    添加
                </el-button>
                <el-button @click="resetForm(ruleFormRef)">重置</el-button>
            </el-form-item>
        </el-form>
    </el-dialog>

    <!-- 编辑弹窗区域 -->
    <el-dialog v-model="UpdateDialog" title="修改网格人员" width="500">
        {{ ruleForm }}
        <el-form ref="ruleFormRef" style="max-width: 600px" :model="ruleForm" :rules="rules" label-width="auto">
            <el-form-item label="部门名称" style="width: 460px;" prop="departmentId">

                <el-cascader style="width: 460px;" v-model="ruleForm.departmentId" :options="options1"
                    :props="props1" />
            </el-form-item>
            <el-form-item label="姓名" prop="realName">
                <el-input v-model="ruleForm.realName" />
            </el-form-item>
            <el-form-item label="身份证号" prop="cardId">
                <el-input v-model="ruleForm.cardId" />
            </el-form-item>
            <el-form-item label="联系方式" prop="phoneNo">
                <el-input v-model="ruleForm.phoneNo" @blur="setAccount()" />
            </el-form-item>

            <el-form-item label="账号" prop="accountName">
                <el-input v-model="ruleForm.accountName" />
            </el-form-item>

            <el-form-item label="角色" prop="roleId">
                <el-radio-group v-model="ruleForm.roleId">
                    <el-radio :value="3">网格长</el-radio>
                    <el-radio :value="4">网格员</el-radio>
                </el-radio-group>
            </el-form-item>

            <el-form-item>
                <el-button type="primary" @click="submitFormUpdate(ruleFormRef)">
                    保存
                </el-button>
                <el-button @click="resetForm(ruleFormRef)">重置</el-button>
            </el-form-item>
        </el-form>
    </el-dialog>




</template>
<script lang="ts" setup>
import axios from 'axios';
import { onMounted, reactive, ref, watch } from 'vue'
import { useCounterStore } from '@/stores/counter';
const pinia = useCounterStore()
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import http from '@/http/axiosHelper';

//定义一个数组,用来装选中的行的数据对象
const selections =ref([])
 const handleSelectionChange = (val: any) => {
  selections.value = val
}


//删除
const del = (row: any) => {



    ElMessageBox.confirm(
        '您确认删除吗?',
        '注意',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(() => {

            http.put('/T6/GridPerson/DelGridPerson', {
                "id": row.id,
                "creator": pinia.loginDto.accountName
            }).then(res => {
                if (res.data.code == 200) {
                    ElMessage.success(res.data.msg);
                    search();
                } else {
                    ElMessage.error(res.data.msg);
                }
            })
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '取消操作',
            })
        })
}




//添加弹窗的级联
const options1 = ref([])
const getOption1 = () => {
    axios.defaults.headers.common.Authorization = 'Bearer ' + pinia.loginDto.jwtToken
    axios.get('http://localhost:5141/api/Department/GetDepartmentTree').then(res => {
        options1.value = res.data.data
    });
}
const props1 = {
    value: 'id',
    label: 'departmentName',
    children: 'children',
    emitPath: false,//数组
    checkStrictly: true
}

//编辑弹窗
const UpdateDialog = ref(false)
const toEdit = (row: any) => {
    //反填数据
    Object.assign(ruleForm, row)
    //再打开弹窗
    UpdateDialog.value = true;

}

//保存修改弹窗的内容
const submitFormUpdate = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            axios.defaults.headers.common.Authorization = 'Bearer ' + pinia.loginDto.jwtToken
            axios.put('http://localhost:5150/api/GridPerson/UpdateGridPerson', ruleForm).then(res => {
                if (res.data.code == 200) {
                    ElMessage.success(res.data.msg);//提示成功
                    //关闭弹窗
                    UpdateDialog.value = false
                    //刷新数据
                    search();
                    //清理ruleform
                    ruleForm.accountName = '';
                    //....
                } else {
                    ElMessage.error(res.data.msg);//提示失败
                }
            })
        } else {
            console.log('error submit!', fields)
        }
    })
}


//添加弹窗
const addDialog = ref(false)
const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive(
    {
        "accountName": "",
        "realName": "",
        "cardId": "",
        "phoneNo": "",
        "departmentId": null,
        "roleId": 4,
        "creator": pinia.loginDto.accountName
    }
)

const rules = reactive<FormRules>({
    departmentId: [
        { required: true, message: '请选择部门名称', trigger: 'blur' }
    ],
    realName: [
        { required: true, message: '请输入姓名', trigger: 'blur' },
        { min: 2, max: 10, message: "姓名长度为2-10位", trigger: 'blur' }
    ],
    cardId: [
        { required: true, message: '请输入身份证号', trigger: 'blur' },
        { min: 18, max: 18, message: "身份证号长度为18位", trigger: 'blur' }
    ],
    phoneNo: [
        { required: true, message: '请输入手机号', trigger: 'blur' },
        { pattern: /^1[3-9]\d{9}$/, message: '请输入格式正确的手机号', trigger: 'blur' }
    ],
    accountName: [
        { required: true, message: '请输入账号', trigger: 'blur' },
        { min: 2, max: 11, message: "账号长度为2-11位", trigger: 'blur' }
    ],
})

const setAccount = () => {
    if (ruleForm.accountName.length == 0) {
        ruleForm.accountName = ruleForm.phoneNo
    }
}

const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            axios.defaults.headers.common.Authorization = 'Bearer ' + pinia.loginDto.jwtToken
            axios.post('http://localhost:5150/api/GridPerson/CreateGridPerson', ruleForm).then(res => {
                if (res.data.code == 200) {
                    ElMessage.success(res.data.msg);//提示成功
                    //关闭弹窗
                    addDialog.value = false
                    //刷新数据
                    search();
                    //清理ruleform
                    ruleForm.accountName = '';
                    //....
                } else {
                    ElMessage.error(res.data.msg);//提示成功
                }
            })
        } else {
            console.log('error submit!', fields)
        }
    })
}

const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
}




const options = ref([])//搜索表单的部门级联的数据源
const getOption = () => {
    axios.defaults.headers.common.Authorization = 'Bearer ' + pinia.loginDto.jwtToken;
    axios.get('http://localhost:5141/api/Department/GetDepartmentTree').then(res => {
        options.value = res.data.data

    })
}


const formInline = reactive({
    RealName: '',
    DepartmentId: null
})

const page = reactive({
    PageIndex: 1,
    PageSize: 3,
    totalCount: 0
})
watch(page, () => {
    search();
})

const props = {
    value: 'id',
    label: 'departmentName',
    children: 'children',
    checkStrictly: true,//可选任意一级
    emitPath: false //false:绑定节点值,而不是整个菜单组成数组
}

const tableData = ref([])

//查询列表数据,作为表格的数据源
const search = () => {
    axios.defaults.headers.common.Authorization = 'Bearer ' + pinia.loginDto.jwtToken;
    axios.get('http://localhost:5141/api/GridPerson/GetGridPerson',
        {
            params: {
                RealName: formInline.RealName,
                DepartmentId: formInline.DepartmentId,
                PageIndex: page.PageIndex,
                PageSize: page.PageSize
            }
        }).then(res => {
            tableData.value = res.data.pageDatas
            page.totalCount = res.data.totalCount
        })
}

//重置行内表达
const reset = () => {
    formInline.DepartmentId = null;
    formInline.RealName = ''

}

onMounted(() => {
    getOption();
    search();
    getOption1();
})
</script>

<style>
.demo-form-inline .el-input {
    --el-input-width: 220px;
}

.demo-form-inline .el-select {
    --el-select-width: 220px;
}
</style>